//让taskForm的按钮无效化
function disableFormBtn() {
    Ext.getCmp('saveAndSendTaskButton').setDisabled(true);
    Ext.getCmp('saveTaskButton').setDisabled(true);
    Ext.getCmp('resertTaskForm').setDisabled(true);
    Ext.getCmp('attachedUploadFiel').setDisabled(true);
}

// 让taskForm的按钮有效化
function enableFormBtn() {
    Ext.getCmp('saveAndSendTaskButton').setDisabled(false);
    Ext.getCmp('saveTaskButton').setDisabled(false);
    Ext.getCmp('resertTaskForm').setDisabled(false);
    Ext.getCmp('attachedUploadFiel').setDisabled(false);
}

// 用于新建任务的时候调整表单来出现使用
function suitTaskFormForCreate() {
    chooseReceiverGrid.setSelection();// 清空收件人选项列表的选项
    // 让表单的所有东西都可用
    taskForm.items.each(function (item) {
        item.setDisabled(false);
    });
    enableFormBtn();
    Ext.getCmp('centerRegion').removeAll(false);// 先移除原有的items,不然直接添加会叠加,如果设置为true就是会自动销毁之前的组件，之后就无法在使用这个组件了
    taskId = Ext.create("MyApp.data.MyModelX").data.id.replace(/-/g, "");// 生成任务Id
    taskCreateOrUpdate = 0;// 说明这是新建操作
    taskForm.getForm().reset();
    attachedStore.removeAll();
    Ext.getCmp('centerRegion').add(taskForm);
}

function getTaskDetialForReceiver(record) {
    if (record.get('isNull') == 0) {
        Ext.Ajax
            .request({
                url: zuulUrl + '/' + taskServiceName + '/taskDetailForReceiver/'
                    + record.get('id') + '/' + currentUserId,
                async: false, // ASYNC 是否异步( TRUE 异步 , FALSE 同步)
                success: function (response, opts) {
                    var obj = Ext.decode(response.responseText);
                    if (record.get('statusName') == '未读') {//点开了未读任务之后要把未读数量更新
                        taskTabPanel.down('#receiveTab').noReadCount--;
                        taskNoReadSettle(taskTabPanel.down('#receiveTab').noReadCount);
                    }
                    var data = {
                        'id': obj.task.id,
                        'name': obj.task.name,
                        'responsible': obj.task.responsible,
                        'typeName': obj.task.typeName,
                        'statusName': obj.task.statusName,
                        'priorityName': obj.task.priorityName,
                        'isGroup': obj.task.isGroup,
                        'description': obj.task.description,
                        'isAttachment': obj.task.isAttachment,
                        'createDate': obj.task.createDate,
                        'receivers': obj.receivers,
                        'attached': obj.attached,
                        'isNull': 1
                    };
                    record.set(data);
                },
                failure: function (response, opts) {
                    Ext.Msg.alert("错误", "该功能暂时不可用！");
                }
            });
    }

}

function getTaskDetialForResponsible(record) {
    if (record.get('isNull') == 0) {
        Ext.Ajax
            .request({
                url: zuulUrl + '/' + taskServiceName + '/taskDetailForResponsible/'
                    + record.get('id'),
                async: false, // ASYNC 是否异步( TRUE 异步 , FALSE 同步)
                success: function (response, opts) {
                    var obj = Ext.decode(response.responseText);
                    var data = {
                        'id': obj.task.id,
                        'name': obj.task.name,
                        'responsible': obj.task.responsible,
                        'typeName': obj.task.typeName,
                        'statusName': obj.task.statusName,
                        'priorityName': obj.task.priorityName,
                        'isGroup': obj.task.isGroup,
                        'description': obj.task.description,
                        'isAttachment': obj.task.isAttachment,
                        'createDate': obj.task.createDate,
                        'receivers': obj.receivers,
                        'attached': obj.attached,
                        'isNull': 1
                    };
                    record.set(data);
                },
                failure: function (response, opts) {
                    Ext.Msg.alert("错误", "该功能暂时不可用！");
                }
            });
    }

}

function downloadAtta(hashOrUuid, name, fileType) {
// var object = new Object();
// object['hashOrUuid'] = hashOrUuid;
// object['fileType'] = fileType;
// var json = encodeURI(Ext.JSON.encode(object));
// a = document.createElement('a');// 创建a标签
// a.href =
// 'http://192.168.32.254:8761/task/getAttached?hashOrUuid='+hashOrUuid+'&fileType='+fileType;//
// 指定下载链接
// a.download = name;
// a.click();// 触发下载
// a.remove();// 除a标签
// Ext.Ajax.request({
// url:
// 'http://192.168.32.254:8761/task/getAttached?hashOrUuid='+hashOrUuid+'&fileType='+fileType,
// async: true, // ASYNC 是否异步(
// // TRUE 异步 ,
// // FALSE 同步)
// //dataType:'blob',
// success: function (response, opts) {
// console.log(response);
// //var blob = new Blob([response.responseText]);
// var reader = new FileReader();
// reader.readAsDataURL(response.responseText); // 转换为base64，可以直接放入a标签href
// reader.onload = function (e) {
// var a = document.createElement('a'); // 转换完成，创建一个a标签用于下载
// a.download = name;
// a.href = e.target.result;
// //$("body").append(a); // 修复firefox中无法触发click
// a.click();
// a.remove();
// }
// // objectUrl = window.URL.createObjectURL(blob);// 创建新的URL表示指定Blob对象
// // a = document.createElement('a');// 创建a标签
// // a.href = objectUrl;// 指定下载链接
// // a.download=name;
// // a.click();// 触发下载
// // a.remove();// 除a标签
// // window.URL.revokeObjectURL(objectUrl);// 释放
// //}
// },
// failure: function (response, opts) {
// Ext.Msg.alert('失败', '该功能暂时不可用！');
// }
// });

    var url = zuulUrl + '/' + taskServiceName + '/attached/' + fileType + '/' + hashOrUuid;      // 【全部导出】请求url
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    // xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
    xhr.responseType = "blob";   // 返回类型blob
    xhr.onload = function () {   // 定义请求完成的处理函数
        if (this.status === 200) {
            var blob = this.response;
            var reader = new FileReader();
            reader.readAsDataURL(blob);   // 转换为base64，可以直接放入a标签href
            reader.onload = function (e) {
                var a = document.createElement('a');   // 转换完成，创建一个a标签用于下载
                a.download = name;
                a.href = e.target.result;
                // $("body").append(a); // 修复firefox中无法触发click
                a.click();
                a.remove();
            }
        } else
            Ext.Msg.alert('失败', '服务器故障');
    };
    xhr.send();
}

//保存任务
function taskSaveOrCommit(isCommit) {
    Ext.getCmp('attachedUploadFiel').setDisabled(true);//先让附件框不可用,不然会校验不通过
    var taskForm = Ext.getCmp('taskForm').getForm();
    if (taskForm.isValid()) {//判断各种信息填写完整没有
        //点击按钮后让这些按钮不可用,防止用户重复点击
        disableFormBtn();
        var selectArray = chooseReceiverGrid.getSelectionModel().getSelected(); //得到收件人被选择的行的数组.
        var receiverArray = new Array();
        Ext.each(selectArray.items, function (result) {
            receiverArray.push(result.data.id);
        });
        var result = new Object();
        var task = new Object();
        var attachArray = new Array();
        task['id'] = taskId;
        task['name'] = Ext.getCmp('taskName').getValue(),
            task['responsible'] = currentUserId;
        task['isGroup'] = Ext.getCmp('isGroup').lastValue.isGroup;
        task['type'] = Ext.getCmp('taskType').getValue(),
            task['status'] = isCommit ? 1 : 0,
            task['description'] = Ext.getCmp('taskDescription').getValue();
        task['priority'] = Ext.getCmp('taskPriority').getValue();
        result['task'] = task;
        result['receivers'] = receiverArray;
        Ext.each(attachedStore.getData().items, function (atta) {
            var data = new Object();
            data['id'] = atta.data.id;
            data['fileType'] = atta.data.fileType;
            data['uuid'] = atta.data.uuid;
            data['attachedName'] = atta.data.attachedName;
            data['taskId'] = taskId;
            attachArray.push(data);
        });
        result['attacheds'] = attachArray;
        Ext.Ajax.request({
            method: taskCreateOrUpdate == 0 ? 'post' : 'put',
            url: zuulUrl + '/' + taskServiceName,
            async: false,   //ASYNC 是否异步( TRUE 异步 , FALSE 同步)
            waitMsg: isCommit ? '正在发布中...' : '正在保存中...',
            defaultXdrContentType: 'application/json',
            jsonData: JSON.stringify(result),
            success: function (response, opts) {
                if (taskCreateOrUpdate == 0) {//判断是不是新建任务
                    var record = {
                        id: taskId,
                        name: Ext.getCmp('taskName').getValue(),
                        statusName: isCommit ? '未读' : '编辑中',
                        priorityName: Ext.getCmp('taskPriority').getRawValue(),
                        isNull: 0,
                        createDate: new Date()
                    };//时间由前端自己生成
                    taskResponseListStore.insert(0, record);//手动修改本地store
                } else {//如果是编辑任务则要手动修改个别数据
                    var index = taskResponseListStore.find('id', taskId);
                    taskResponseListStore.getAt(index).set('name', Ext.getCmp('taskName').getValue());
                    taskResponseListStore.getAt(index).set('statusName', isCommit ? '未读' : '编辑中');
                    taskResponseListStore.getAt(index).set('priorityName', Ext.getCmp('taskPriority').getRawValue());
                    taskResponseListStore.getAt(index).set('isNull', '0');
                }
                Ext.Msg.alert("成功", isCommit ? '发布成功' : '保存成功');
                taskCreateOrUpdate = 1;//保存完就修改全局状态
            },
            failure: function (form, action) {
                Ext.Msg.alert("错误", '该功能暂时不可用！');
            }
        });
    } else {
        Ext.Msg.alert('错误', '任务信息请填写完全！');
    }
    enableFormBtn();//让taskForm的按钮有效化
    Ext.getCmp('attachedUploadFiel').setDisabled(false);//首尾呼应
}

//设置任务的未读提醒状态
function taskNoReadSettle(count) {
    if (count <= 0) {
        taskTabPanel.down('#receiveTab').setTitle('我的任务');
        taskTabPanel.down('#receiveTab').setIcon('static/images/icons/fam/noTip.ico');
    } else {
        taskTabPanel.down('#receiveTab').setTitle('我的任务(未读:' + count + '条)');
        taskTabPanel.down('#receiveTab').setIcon('static/images/icons/fam/tip.ico');
    }
    taskTabPanel.down('#receiveTab').noReadCount = count;
}